<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧任务列表区域 -->
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span class="card-title">我的任务列表</span>
            <el-input
              v-model="queryParams.orderNo"
              placeholder="请输入工单号"
              clearable
              size="small"
              style="width: 200px; margin-left: 10px"
              @keyup.enter.native="handleQuery"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
            </el-input>
            <el-button type="primary" plain size="mini" icon="el-icon-refresh" @click="getTaskList" style="margin-left: 10px">刷新</el-button>
          </div>
          
          <!-- 任务列表 -->
          <div class="task-list">
            <el-radio-group v-model="taskFilter" @change="handleTaskFilterChange">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="0">未开始</el-radio-button>
              <el-radio-button label="1">已派工</el-radio-button>
              <el-radio-button label="2">进行中</el-radio-button>
              <el-radio-button label="3">已完成</el-radio-button>
              <el-radio-button label="4">已暂停</el-radio-button>
            </el-radio-group>
            
            <el-divider></el-divider>
            
            <div v-if="taskList.length === 0" class="empty-list">
              <i class="el-icon-document"></i>
              <p>暂无任务</p>
            </div>
            
            <div v-else class="task-items">
              <el-card 
                v-for="(item, index) in taskList" 
                :key="index" 
                shadow="hover" 
                :class="['task-item', { 'active-task': currentTask && currentTask.id === item.id }]"
                @click.native="handleSelectTask(item)"
              >
                <div class="task-header">
                  <span class="task-id">工单号: {{ item.workOrderCode }}</span>
                  <el-tag :type="getStatusType(item.status)" size="mini">{{ getStatusText(item.status) }}</el-tag>
                </div>
                <div class="task-content">
                  <div class="task-info">
                    <p><i class="el-icon-s-goods"></i> 产品: {{ item.productName }}</p>
                    <p><i class="el-icon-s-operation"></i> 工序: {{ item.taskName }}</p>
                    <p><i class="el-icon-s-data"></i> 计划数量: {{ item.planQuantity }}</p>
                    <p><i class="el-icon-finished"></i> 已完成: {{ item.actualProduction }}</p>
                  </div>
                </div>
                <div class="task-footer">
                  <el-button
                    v-if="item.status === '0' || item.status === '1'"
                    type="primary"
                    size="mini"
                    @click.stop="handleStartTask(item)"
                  >开工</el-button>
                  <el-button
                    v-else-if="item.status === '2'"
                    type="success"
                    size="mini"
                    @click.stop="handleReportTask(item)"
                  >报工</el-button>
                </div>
              </el-card>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧操作区域 -->
      <el-col :span="16">
        <el-card class="box-card" v-if="currentTask">
          <div slot="header" class="clearfix">
            <span class="card-title">当前任务</span>
            <el-tag :type="getStatusType(currentTask.status)" style="margin-left: 10px">{{ getStatusText(currentTask.status) }}</el-tag>
          </div>
          
          <div class="task-detail">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="工单号">{{ currentTask.workOrderCode }}</el-descriptions-item>
              <el-descriptions-item label="产品名称">{{ currentTask.productName }}</el-descriptions-item>
              <el-descriptions-item label="工序">{{ currentTask.taskName }}</el-descriptions-item>
              <el-descriptions-item label="计划数量">{{ currentTask.planQuantity }}</el-descriptions-item>
              <el-descriptions-item label="已完成数量">{{ currentTask.actualProduction }}</el-descriptions-item>
              <el-descriptions-item label="待完成数量">{{ currentTask.planQuantity - currentTask.actualProduction }}</el-descriptions-item>
              <el-descriptions-item label="开始时间" v-if="currentTask.planStartTime">{{ currentTask.planStartTime }}</el-descriptions-item>
              <el-descriptions-item label="操作人">{{ currentTask.createBy }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="action-buttons" style="margin-top: 20px">
              <el-button
                v-if="currentTask.status === '0'"
                type="primary"
                icon="el-icon-video-play"
                @click="handleStartTask(currentTask)"
              >开始任务</el-button>

              <el-button
                v-if="currentTask.status === '1'"
                type="primary"
                icon="el-icon-video-play"
                @click="handleStartTask(currentTask)"
              >开工</el-button>

              <el-button
                v-if="currentTask.status === '2'"
                type="success"
                icon="el-icon-finished"
                @click="handleReportTask(currentTask)"
              >报工</el-button>

              <el-button
                v-if="currentTask.status === '2'"
                type="warning"
                icon="el-icon-warning-outline"
                @click="handleReportException"
              >异常上报</el-button>
            </div>
          </div>
        </el-card>
        
        <el-empty v-else description="请选择一个任务"></el-empty>
      </el-col>
    </el-row>
    
    <!-- 报工对话框 -->
    <el-dialog :title="'报工 - ' + (currentTask ? currentTask.workOrderCode : '')" :visible.sync="reportDialogVisible" width="650px" append-to-body>
      <el-form ref="reportForm" :model="reportForm" :rules="reportRules" label-width="100px">
        <el-form-item label="良品数量" prop="goodQty">
          <el-input-number v-model="reportForm.goodQty" :min="0" :max="currentTask ? currentTask.planQuantity : 0" controls-position="right"></el-input-number>
        </el-form-item>
        
        <el-form-item label="不良品数量" prop="scrapQty">
          <el-input-number v-model="reportForm.scrapQty" :min="0" controls-position="right" @change="handleScrapQtyChange"></el-input-number>
        </el-form-item>
        
        <!-- 不良品明细 -->
        <div v-if="reportForm.scrapQty > 0" class="scrap-details">
          <el-divider content-position="left">不良品明细</el-divider>
          
          <el-table :data="reportForm.scrapDetails" border style="width: 100%">
            <el-table-column label="不良原因" prop="reasonName" width="180">
              <template slot-scope="scope">
                <el-select v-model="scope.row.reasonCode" placeholder="请选择不良原因" @change="(val) => handleReasonChange(val, scope.$index)">
                  <el-option
                    v-for="item in defectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.qty" :min="1" :max="reportForm.scrapQty" size="mini" @change="calculateTotalScrap"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleRemoveScrapDetail(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="scrap-summary" style="margin-top: 10px; display: flex; justify-content: space-between; align-items: center;">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddScrapDetail">新增不良明细</el-button>
            <div class="scrap-total">
              <span>已分配: {{ totalScrapQty }} / {{ reportForm.scrapQty }}</span>
              <el-progress :percentage="scrapPercentage" :status="scrapPercentage === 100 ? 'success' : 'warning'"></el-progress>
            </div>
          </div>
        </div>
        
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="reportForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reportDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReport" :disabled="!isReportFormValid">确 认</el-button>
      </div>
    </el-dialog>
    
    <!-- 异常上报对话框 -->
    <el-dialog title="异常上报" :visible.sync="exceptionDialogVisible" width="500px" append-to-body>
      <el-form ref="exceptionForm" :model="exceptionForm" :rules="exceptionRules" label-width="100px">
        <el-form-item label="异常类型" prop="exceptionType">
          <el-select v-model="exceptionForm.exceptionType" placeholder="请选择异常类型">
            <el-option
              v-for="item in exceptionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="异常描述" prop="description">
          <el-input type="textarea" v-model="exceptionForm.description" placeholder="请详细描述异常情况"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exceptionDialogVisible = false">取 消</el-button>
        <el-button type="warning" @click="submitException">确认上报</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getReportableList, finishTask, reportException } from "@/api/sc/report";
import { startWorkOrderTask } from "@/api/sc/workOrderTask";

export default {
  name: "WorkReport",
  data() {
    return {
      // 查询参数
      queryParams: {
        orderNo: "",
        status: "",
        pageNum: 1,
        pageSize: 10
      },
      
      // 任务列表过滤
      taskFilter: "all",
      
      // 任务列表数据
      taskList: [],
      
      // 当前选中的任务
      currentTask: null,
      
      // 报工对话框
      reportDialogVisible: false,
      reportForm: {
        goodQty: 0,
        scrapQty: 0,
        scrapDetails: [],
        remark: ""
      },
      
      // 表单校验规则
      reportRules: {
        goodQty: [
          { required: true, message: "请输入良品数量", trigger: "blur" }
        ],
        scrapQty: [
          { required: true, message: "请输入不良品数量", trigger: "blur" }
        ]
      },
      
      // 不良原因选项
      defectOptions: [
        { value: "SC-001", label: "表面划伤" },
        { value: "SC-002", label: "尺寸超差" },
        { value: "SC-003", label: "功能异常" },
        { value: "SC-004", label: "漏装零件" },
        { value: "SC-005", label: "装配错误" }
      ],
      
      // 异常上报对话框
      exceptionDialogVisible: false,
      exceptionForm: {
        exceptionType: "",
        description: ""
      },
      
      // 异常校验规则
      exceptionRules: {
        exceptionType: [
          { required: true, message: "请选择异常类型", trigger: "change" }
        ],
        description: [
          { required: true, message: "请输入异常描述", trigger: "blur" }
        ]
      },
      
      // 异常类型选项
      exceptionOptions: [
        { value: "EQ-001", label: "设备故障" },
        { value: "MT-001", label: "物料短缺" },
        { value: "QC-001", label: "质量问题" },
        { value: "OT-001", label: "其他异常" }
      ]
    };
  },
  computed: {
    // 不良品总数
    totalScrapQty() {
      return this.reportForm.scrapDetails.reduce((sum, item) => sum + item.qty, 0);
    },
    
    // 不良品分配比例
    scrapPercentage() {
      if (this.reportForm.scrapQty === 0) return 0;
      return Math.min(100, Math.round((this.totalScrapQty / this.reportForm.scrapQty) * 100));
    },
    
    // 报工表单是否有效
    isReportFormValid() {
      if (this.reportForm.scrapQty > 0) {
        // 如果有不良品，必须全部分配完成
        return this.scrapPercentage === 100;
      }
      return true;
    }
  },
  created() {
    this.getTaskList();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/report' || to.name === 'WorkReport') {
        console.log('生产报工页面路由变化，刷新数据');
        this.getTaskList();
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('生产报工查询参数变化，刷新数据');
          this.getTaskList();
        }
      },
      deep: true
    }
  },
  methods: {
    // 获取任务列表
    getTaskList() {
      this.loading = true;
      getReportableList(this.queryParams).then(response => {
        this.taskList = response.data;
        console.log("从后端获取的任务列表数据:", this.taskList); // 添加这一行
        this.loading = false;
        
        // 处理从任务列表跳转过来的情况
        const { taskId } = this.$route.query;
        if (taskId) {
            const task = this.taskList.find(item => item.workOrderTaskId == taskId);
            if (task) {
                this.currentTask = task;
            }
        }
      });
    },
    
    // 处理查询
    handleQuery() {
      this.getTaskList();
    },
    
    // 处理任务过滤变化
    handleTaskFilterChange(value) {
      this.queryParams.status = value === "all" ? "" : value;
      this.getTaskList();
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        '0': "info",     // 未开始
        '1': "warning",  // 已派工
        '2': "primary",  // 进行中
        '3': "success",  // 已完成
        '4': "danger"    // 已暂停
      };
      return statusMap[status] || "info";
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '0': "未开始",
        '1': "已派工",  // 已派工但未开工
        '2': "进行中",  // 已开工但未报工
        '3': "已完成",  // 已报工完成
        '4': "已暂停"   // 暂停状态
      };
      return statusMap[status] || "未知";
    },
    
    // 选择任务
    handleSelectTask(task) {
      this.currentTask = task;
    },
    
    // 开始任务
    handleStartTask(task) {
      this.$confirm(`确认开始工单 ${task.workOrderCode} 的 ${task.taskName} 工序?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 调用后端API开始任务
        startWorkOrderTask(task.workOrderTaskId).then(response => {
          if (response.code === 200) {
            this.$message.success("任务开工成功");
            this.getTaskList(); // 刷新任务列表
          } else {
            this.$message.error(response.msg || "任务开工失败");
          }
        }).catch(error => {
          console.error("开工任务失败:", error);
          this.$message.error("操作失败，请稍后重试");
        });
      }).catch(() => {});
    },
    
    // 报工
    handleReportTask(task) {
      this.currentTask = task;
      this.reportForm = {
        goodQty: 0,
        scrapQty: 0,
        scrapDetails: [],
        remark: ""
      };
      this.reportDialogVisible = true;
    },
    
    // 处理不良品数量变化
    handleScrapQtyChange(value) {
      // 如果不良品数量为0，清空不良品明细
      if (value === 0) {
        this.reportForm.scrapDetails = [];
      }
    },
    
    // 添加不良品明细
    handleAddScrapDetail() {
      this.reportForm.scrapDetails.push({
        reasonCode: "",
        reasonName: "",
        qty: 1
      });
      this.calculateTotalScrap();
    },
    
    // 移除不良品明细
    handleRemoveScrapDetail(index) {
      this.reportForm.scrapDetails.splice(index, 1);
      this.calculateTotalScrap();
    },
    
    // 处理不良原因变化
    handleReasonChange(value, index) {
      const option = this.defectOptions.find(item => item.value === value);
      if (option) {
        this.reportForm.scrapDetails[index].reasonName = option.label;
      }
    },
    
    // 计算不良品总数
    calculateTotalScrap() {
      // 已在计算属性中实现
    },
    
    // 提交报工
    submitReport() {
      this.$refs.reportForm.validate(valid => {
        if (valid) {
          // 校验不良品明细是否分配完整
          if (this.reportForm.scrapQty > 0 && this.scrapPercentage !== 100) {
            this.$message.warning("不良品明细数量与不良品总数不一致，请检查");
            return;
          }

          const reportData = {
            workOrderTaskId: this.currentTask.workOrderTaskId,
            goodQty: this.reportForm.goodQty,
            scrapQty: this.reportForm.scrapQty,
            remark: this.reportForm.remark
          };

          this.$modal.loading("正在提交报工...");
          finishTask(reportData).then(response => {
            this.$modal.closeLoading();
            if (response.code === 200) {
              this.$modal.msgSuccess("报工成功");
              this.reportDialogVisible = false;
              this.getTaskList(); // 刷新任务列表
              this.currentTask = null; // 清空当前任务
            } else {
              this.$modal.msgError(response.msg || "报工失败");
            }
          }).catch(() => {
            this.$modal.closeLoading();
          });
        }
      });
    },
    
    // 异常上报
    handleReportException() {
      this.exceptionForm = {
        exceptionType: "",
        description: ""
      };
      this.exceptionDialogVisible = true;
    },
    
    // 提交异常
    submitException() {
      this.$refs.exceptionForm.validate(valid => {
        if (valid) {
          // 调用后端API提交异常
          // 模拟API调用
          setTimeout(() => {
            this.exceptionDialogVisible = false;
            this.$message.success("异常已上报");
          }, 500);
        }
      });
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 根据任务ID和工单号加载任务详情
    loadTaskDetails(taskId, orderNo, processName) {
      this.loading = true;
      
      // 这里应该调用后端API获取任务详情
      // 模拟API调用
      setTimeout(() => {
        // 模拟从后端获取的任务数据
        const task = {
          id: taskId,
          orderNo: orderNo,
          productName: "从任务页面跳转的产品",
          processName: processName || "未知工序",
          planQty: 100,
          finishedQty: 0,
          status: "processing", // 假设任务状态为"生产中"
          startTime: this.formatDateTime(new Date()),
          operatorName: "当前用户"
        };
        
        // 将任务添加到列表中
        this.taskList = [task];
        
        // 自动选中该任务
        this.handleSelectTask(task);
        
        this.loading = false;
      }, 500);
    }
  }
};
</script>

<style scoped>
.card-title {
  font-size: 16px;
  font-weight: bold;
}

.task-list {
  margin-top: 10px;
}

.task-items {
  margin-top: 15px;
  max-height: 600px;
  overflow-y: auto;
}

.task-item {
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.task-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.active-task {
  border: 2px solid #409EFF;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-id {
  font-weight: bold;
}

.task-content {
  margin-bottom: 10px;
}

.task-info p {
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.task-info p i {
  margin-right: 5px;
  color: #409EFF;
}

.task-footer {
  display: flex;
  justify-content: flex-end;
}

.empty-list {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}

.empty-list i {
  font-size: 30px;
  margin-bottom: 10px;
}

.task-detail {
  margin-top: 20px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.scrap-details {
  margin-top: 15px;
  padding: 10px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.scrap-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.scrap-total {
  width: 200px;
  text-align: right;
}
</style> 